package com.wuyan.warriorsoffate

import android.Manifest
import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS
import androidx.activity.ComponentActivity
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.compose.setContent
import androidx.activity.result.contract.ActivityResultContracts
import androidx.activity.viewModels
import androidx.annotation.RequiresApi
import androidx.compose.animation.ExperimentalAnimationApi
import androidx.compose.foundation.layout.*
import androidx.compose.material.*
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.onFocusChanged
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalLifecycleOwner
import androidx.compose.ui.res.painterResource
import androidx.core.view.WindowCompat
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.navigation.NavType
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.rememberNavController
import androidx.navigation.navArgument
import com.google.accompanist.insets.navigationBarsHeight
import com.google.accompanist.insets.statusBarsHeight
import com.google.accompanist.permissions.ExperimentalPermissionsApi
import com.google.accompanist.permissions.PermissionRequired
import com.google.accompanist.permissions.rememberPermissionState
import com.google.accompanist.systemuicontroller.rememberSystemUiController
import com.wuyan.warriorsoffate.data.Config
import com.wuyan.warriorsoffate.data.DisplayPage
import com.wuyan.warriorsoffate.data.NesViewModel
import com.wuyan.warriorsoffate.data.NesViewModelBuild
import com.wuyan.warriorsoffate.ui.*
import com.wuyan.warriorsoffate.ui.page.HomePage
import com.wuyan.warriorsoffate.ui.page.PersonInfoPage
import com.wuyan.warriorsoffate.ui.theme.WeTheme
import com.wuyan.warriorsoffate.ui.view.WeButton
import com.wuyan.warriorsoffate.ui.view.WeSurface
import com.wuyan.warriorsoffate.ui.view.WeText

class MainActivity : ComponentActivity() {
    @ExperimentalPermissionsApi
    @ExperimentalAnimationApi
    @RequiresApi(Build.VERSION_CODES.M)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        Config.init(this)
        val model by viewModels<NesViewModel> { NesViewModelBuild(assets) }
        WindowCompat.setDecorFitsSystemWindows(window, false)
        setContent {
            val navController = rememberNavController()
            WeTheme(model.theme){
                rememberSystemUiController().run {
                    setStatusBarColor(WeTheme.colors.bg)
                }
                Column(modifier = Modifier.fillMaxSize()) {
                    Spacer(modifier = Modifier.statusBarsHeight())
                    RequestPermissionUsingAccompanist(Manifest.permission.WRITE_EXTERNAL_STORAGE){
                        NavHost(navController = navController,
                            startDestination=DisplayPage.Main.name, ){
                            composable(
                                route = DisplayPage.Main.name
                            ){
                                HomePage(nes = model,navController)
                            }
                            composable(
                                route = "${DisplayPage.PersonInfo.name}/{id}",
                                arguments = listOf(
                                    navArgument("id"){
                                        type= NavType.IntType
                                    }
                                )
                            ){entry->
                                PersonInfoPage(nes = model,
                                    entry.arguments?.getInt("id")!!,navController,modifier = Modifier.fillMaxSize())
                            }
                        }
                    }

                    Spacer(modifier = Modifier.navigationBarsHeight())
                }
                if (Config.msgInfoSate){
                    AlertDialog(
                        onDismissRequest = {
                            Config.msgInfoSate = false
                        },
                        title = {
                            Box(modifier = Modifier
                                .padding(WeTheme.weDp.paddingMedium)
                                .fillMaxWidth()) {
                                Text(text = "错误信息", modifier = Modifier.align(Alignment.TopCenter))
                            }
                        },
                        text={
                            Text(text = Config.msgInfoText)
                        },
                        buttons = {
                            Box(modifier = Modifier
                                .padding(WeTheme.weDp.paddingMedium)
                                .fillMaxWidth()) {
                                Button(onClick = {
                                    Config.msgInfoSate = false
                                }, modifier = Modifier.align(Alignment.BottomEnd)) {
                                    Text(text = "确认")
                                }
                            }
                        }
                    )
                }
            }
        }
    }

}
//申请权限界面
@ExperimentalPermissionsApi
@Composable
private fun RequestPermissionUsingAccompanist(permission:String,content:@Composable ()->Unit){
    // 定义 Permission State
    val permissionState = rememberPermissionState(permission)
    val context=LocalContext.current
    PermissionRequired(
        permissionState = permissionState,
        permissionNotAvailableContent = {
            // 权限获取失败
            WeSurface(modifier = Modifier.fillMaxSize()) {
                Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center){
                    Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
                        WeButton(
                            onClick = {
                                val packageURI = Uri.parse("package:" + context.packageName)
                                val intent=Intent(ACTION_APPLICATION_DETAILS_SETTINGS,packageURI)
                                context.startActivity(intent)
                            },
                            text = "你始终拒绝了权限跳转到设置页面"
                        )
                    }
                }
            }
        }, permissionNotGrantedContent = {
            // 尚未获取权限时
            WeSurface(modifier = Modifier.fillMaxSize()) {
                Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
                    WeButton(
                        onClick = { permissionState.launchPermissionRequest() },
                        text = "获取文件读写权限，开始使用软件"
                    )
                }
            }
        }, content = {
            // 权限获取成功
            content()
        }
    )
}